<?php

Raise::load('core.ui.RaiseUIControl');
Raise::load('core.ui.RaiseTemplate');
Raise::load('core.structure.RaiseDataTable');
Raise::load('core.reflection.RaiseVariable');

/**
 * RaiseRepeater class
 * Provides a template for data to be repeated
 *
 * @author Sam-Mauris Yong / hellclanner at live dot com
 * @license http://www.opensource.org/licenses/bsd-license New BSD License
 * @package phpraise.control
 * @since 1.2
 */
class RaiseRepeater extends RaiseUIControl {

    /**
     * The template to use for each item in the repeater
     * @var RaiseTemplate
     */
    private $template;

    /**
     * The data to use for the control to populate
     * @var object
     */
    private $data;

    /**
     * Create a new RaiseRepeater
     * @param RaiseTemplate $t (optional) The template to use for each item in the repeater
     * @param RaiseDataTable $d (optional) The data table used to populate the control
     */
    public function __construct($t = null, $d = null){
        if($t instanceof RaiseTemplate){
            $this->template($t);
        }else{
            $this->template(new RaiseTemplate(''));
        }
        if($d){
            $this->data($d);
        }
    }

    /**
     * Get or set the template to use for each item of the repeater
     * @param RaiseTemplate $t (Optional) The template to set
     * @return RaiseTemplate
     */
    public function template($t = null){
        if(func_num_args() == 1){
            if(!($t instanceof RaiseTemplate)){
                throw new RaiseInvalidArgumentException('RaiseRepeater::template() expecting RaiseTemplate as first parameter; ' . RaiseVariable::typeInfo($t) . ' was given instead.');
            }
            $this->template = $t;
        }
        return $this->template;
    }

    /**
     * Get or set the RaiseDataTable of the repeater
     * @param object $d (Optional) The data table to set
     * @return object
     */
    public function data($d = null){
        if(func_num_args() == 1){
            $this->data = $d;
        }
        return $this->data;
    }

    public function output() {
        $buffer = '';

        if($this->data instanceof RaiseCollection){
            $iterator = $this->data->iterator();
            while ($a = $iterator->iterate()){
                foreach($a->value() as $h => $v){
                    $this->template->fields()->add($h, $v);
                }
                $buffer .= $this->template->parse();
                $this->template->fields()->clear();
            }
        }else{
            // single object
            foreach($this->data as $h => $v){
                $this->template->fields()->add($h, $v);
            }
            $buffer .= $this->template->parse();
            $this->template->fields()->clear();
        }

        return $buffer;
    }

}
